
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _ = db.command
export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *     "regionName": "北京市",
   *     "wareName": "成都仓库"
   * }
   */
  //1.校验参数
  if (nw.util.isNull(body.regionName)){
    return fail("请选择地区")
  }
  if (nw.util.isNull(body.wareName)){
    return fail("请存在仓库")
  }
  //2.查询仓库信息和地区信息
  const p1 = nw.db.findByWhereJson({
    dbName:"region",
    whereJson:{name:_.eq(body.regionName),deleted:0}
  })

  const p2 = nw.db.findByWhereJson({
    dbName:"ware",
    whereJson:{name:_.eq(body.wareName),deleted:0}
  })

  const [region,ware] = await Promise.all([p1,p2])
  console.log(region)
  console.log(ware)
  if (nw.util.isNull(region)){
    return fail("地区不存在")
  }
  if (nw.util.isNull(ware)){
    return fail("仓库不存在")
  }
  //3.构建保存信息
  let data = {
    regionId:region._id,
    regionName:region.name,
    wareId:ware._id,
    wareName:ware.name,
    status:1,
    createTime:new Date(),
    updateTime:new Date(),
    deleted:0
  }

  //4.保存数据
  let res = await nw.db.add({
    dbName:"regionWare",
    dataJson:data
  })

  if (nw.util.isNull(res)){
    return fail("保存失败")
  }

  return ok("开通成功")










}
